package com.cksys.achievement.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.cksys.achievement.entity.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * @ClassName: FileUtils
 * @author: zyx
 * @E-mail: 1377631190@qq.com
 * @DATE: 2020/3/8 13:46
 */
@Component
public class FileUtils {

    @Value("${aliyun.accesskey.endpoint}")
    private String endpoint;
    @Value("${aliyun.accesskey.id}")
    private String accessKeyId;
    @Value("${aliyun.accesskey.secret}")
    private String accessKeySecret;
    /**
     * 图片存储路径前缀
     */
    @Value("${aliyun.accesskey.prefix}")
    private String prefix;
    @Value("${aliyun.accesskey.buckerName}")
    private String buckerName;
    @Value("${aliyun.imgPrefix}")
    private String imgPrefix;
    @Value("${aliyun.imgSuffix}")
    private String imgSuffix;

    /**
     * 允许上传的格式
     */
    private static final String[] IMAGE_TYPE = new String[]{"image/tiff", "image/jpg", "image/jpeg", "image/gif", "image/png", "image/fax"};

    /**
     * 存储图片的方法
     * @param img   图片
     * @param user  保存的人，主要是要把id保存
     * @return 返回储存的路径
     */
    public String saveImg(MultipartFile img, User user) throws IOException {
        boolean isLegal = false;
        String contentType = img.getContentType();
        for (String type : IMAGE_TYPE) {
            if (type.equalsIgnoreCase(contentType)) {
                isLegal = true;
                break;  // 只要与允许上传格式其中一个匹配就可以
            }
        }

        if (!isLegal) {
            throw new RuntimeException("图片格式错误!");
        }

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 拼写图片上传后的地址
        String name = img.getName();
        String[] split = name.split("\\.");
        String url = prefix + user.getId() + "/" + split[0] + "_" + System.currentTimeMillis();
        PutObjectRequest putObjectRequest = new PutObjectRequest(buckerName, url, new ByteArrayInputStream(img.getBytes()));

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType("image/jpg");
        putObjectRequest.setMetadata(metadata);

        ossClient.putObject(putObjectRequest);
        ossClient.shutdown();
        return imgPrefix + url + imgSuffix;
    }



}
